package com.qms.repast.commons;

import android.content.Context;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.orhanobut.logger.Logger;
import com.qms.repast.entity.MessageEvent;
import com.qms.repast.entity.resbean.LocationBean;

import org.greenrobot.eventbus.EventBus;

/**
 * @author 泅渡者
 * @date 2018/9/21 0021
 * @describe:
 */
public class AppLocation {
	/**
	 * 声明mlocationClient对象
	 */
	public static AMapLocationClient mlocationClient = null;
	/**
	 * 声明mLocationOption对象
	 */
	public static AMapLocationClientOption mLocationOption = null;

	public static void init (Context context) {
		if (mlocationClient == null) {
			mlocationClient = new AMapLocationClient(context);
		}
		if (mLocationOption == null) {
			mLocationOption = new AMapLocationClientOption();
		}
		//设置定位监听
		mlocationClient.setLocationListener(new AMapLocationListener() {
			@Override
			public void onLocationChanged (final AMapLocation amapLocation) {
				if (amapLocation != null) {
					if (amapLocation.getErrorCode() == 0) {
						LocationBean locationBean = new LocationBean();
						locationBean.setCity(amapLocation.getCity());
						locationBean.setCityId(amapLocation.getCityCode());
						locationBean.setLatitude(amapLocation.getLatitude());
						locationBean.setLongitude(amapLocation.getLongitude());
						EventBus.getDefault().post(new MessageEvent<>(1011, locationBean));
					} else {
						//显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
						Logger.e("location Error, ErrCode:"
										 + amapLocation.getErrorCode() + ", errInfo:"
										 + amapLocation.getErrorInfo());
					}
				}
			}
		});
		//获取一次定位结果：
		//该方法默认为false。
		mLocationOption.setOnceLocation(true);
		//设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
		mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
		//关闭缓存机制
		mLocationOption.setLocationCacheEnable(false);
		//设置是否允许模拟位置,默认为true，允许模拟位置
		mLocationOption.setMockEnable(true);
		//给定位客户端对象设置定位参数
		mlocationClient.setLocationOption(mLocationOption);
	}

	public static void startLocation () {
		if (mlocationClient != null) {
			mlocationClient.startLocation();
		}
	}

	public static void onDestroy () {
		if (mlocationClient != null) {
			mlocationClient.onDestroy();
		}
	}
}
